package password;

import org.apaches.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author jie
 * @version 创建时间：2018年9月13日 下午7:02:19
 * 类说明
 */
public class MD5Utils {
    public static void main(String[] args) {
        String string = null;
        String pwd = md5Str("0000");
        System.out.println(pwd);
//        4a7d1ed414474e4033ac29ccb8653d9b
        System.out.println(DigestUtils.md5Hex("1234"));

        String md5Src = "/Users/macpro/ideaWorkSpace/MyJava/src/password/bee/FC241118370001.dat";
//        String md5SrcFolder = "/Users/macpro/ideaWorkSpace/MyJava/src/password/bee";
        String md5SrcFolder = "/Users/macpro/ideaWorkSpace/MyJava/src/password/bee/nullFolder";
        String folderMD5Sum = getFolderMD5Sum(new File(md5SrcFolder));
        System.out.println("MD5:main:Folder:"+folderMD5Sum);

        String s = md5File(md5Src);
        System.out.println("MD5:main:md5Hex:"+s);

        String fileMD5 = md5File2(md5Src);
        System.out.println("MD5:main:"+fileMD5+" "+(fileMD5.equals(s)));
    }



    //测试 请求数据MD5
    private static void testReqMd5() {
        HashMap<String, String> reqMap = new HashMap<>();

        String sign = sign(reqMap);
        System.out.println("sign==" + sign);
    }

    private static String sign(Map<String, String> map) {
        final Map<String, String> parameterMap = new TreeMap<String, String>();

        for (Map.Entry<String, String> entity : map.entrySet()) {
            parameterMap.put(entity.getKey(), entity.getValue());
        }
        parameterMap.put("appid", "lPC35CDi9fdJPg4Z");
        parameterMap.put("appkey", "80SVyESWgeruBaQkJR5GChhdfAYBTk20");
        parameterMap.put("payload", "{\"device-uuid\":\"C1030341744156\",\"slot-id\":\"25000282\",\"quantity\":1,\"type\":\"IMG\",\"ip\":\"182.48.111.219\",\"longitude\":\"\",\"latitude\":\"\"}");
        parameterMap.put("sequence", "1555466758");
        parameterMap.put("timestamp", "1555466758000");
        parameterMap.put("version", "1.3");
        StringBuilder stb = new StringBuilder();
        for (Map.Entry<String, String> entity : parameterMap.entrySet()) {
            stb.append(entity.getKey()).append("=").append(entity.getValue()).append("&");
        }

        String str = stb.toString();
        System.out.println(str);

        return DigestUtils.md5Hex(str.substring(0, str.length() - 1));
    }

    //md5 string
    public static String md5Str(String str) {
        if (str == null || str.length()<1)return null;
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] byteArray = digest.digest(str.getBytes());
            String hexString = "";
            byte[] bytes = byteArray;
            int var5 = byteArray.length;

            for(int i = 0; i < var5; ++i) {
                byte b = bytes[i];
                int temp = b & 255;
                if (temp < 16 && temp >= 0) {
                    hexString = hexString + "0" + Integer.toHexString(temp);
                } else {
                    hexString = hexString + Integer.toHexString(temp);
                }
            }

            return hexString;
        } catch (Exception var9) {
            var9.printStackTrace();
            if (var9 instanceof NullPointerException) {
                throw new NullPointerException();
            } else {
                return "";
            }
        }
    }

    //idea md5Hex 与 macbook md5sum命令 结果一致：2022-12-01 19:53:03
    //idea 环境 与 mac md5sum terminal结果一致。 2023-03-01 10:18:48
    public static String md5File(String filePath){
        try {
            return DigestUtils.md5Hex(new FileInputStream(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @see MD5Utils#md5File(java.lang.String) //结果一样。上面的方法。
     * 与 macbook md5sum命令 结果一致：2022-12-01 19:53:03
     * @param path
     * @return
     */
    public static String md5File2(String path) {
        BigInteger bi = null;
        try {
            byte[] buffer = new byte[8192];
            int len = 0;
            MessageDigest md = MessageDigest.getInstance("MD5");
            File f = new File(path);
            FileInputStream fis = new FileInputStream(f);
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            fis.close();
            byte[] b = md.digest();
            bi = new BigInteger(1, b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi.toString(16);
    }


    //是多个 文件的md5的和。 
    public static String getFolderMD5Sum(File file) {
        if (file == null || !file.exists()) return "";
        if (file.isDirectory()){
            StringBuffer sb = new StringBuffer();
            File[] files = file.listFiles();
            if (files != null && files.length>0) {
                for (File fileSon:files) {
                    if (fileSon.isDirectory()){
                        sb.append(getFolderMD5Sum(fileSon));
                    }else {
                        sb.append(md5File(fileSon.getAbsolutePath()));
                    }
                }
            }
            return sb.toString();
        }else {
            return md5File(file.getAbsolutePath());
        }
    }
}
